import os
import json
import logging
from datetime import datetime
from .utils import get_database_path, get_faces_dir, validate_name

class FaceDatabase:
    def __init__(self):
        """初始化人脸数据库"""
        self.db_file = get_database_path()
        self.faces_dir = get_faces_dir()
        self.data = self.load()
        
    def load(self):
        """加载数据库"""
        if os.path.exists(self.db_file):
            try:
                with open(self.db_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                # 验证数据库结构
                if not isinstance(data, dict) or 'persons' not in data:
                    data = {'persons': [], 'version': '1.0'}
                if 'version' not in data:
                    data['version'] = '1.0'
                return data
            except Exception as e:
                logging.error(f"加载人脸数据库失败: {e}")
                return {'persons': [], 'version': '1.0'}
        return {'persons': [], 'version': '1.0'}
    
    def save(self):
        """保存数据库"""
        try:
            with open(self.db_file, 'w', encoding='utf-8') as f:
                json.dump(self.data, f, indent=2, ensure_ascii=False)
            logging.info("人脸数据库已保存")
            return True
        except Exception as e:
            logging.error(f"保存人脸数据库失败: {e}")
            return False
    
    def add_person(self, name, face_images=None):
        """添加新人员"""
        if not validate_name(name):
            return False, "无效的人名"
            
        # 检查是否已存在
        if any(p['name'] == name for p in self.data['persons']):
            return False, f"人员 '{name}' 已存在"
            
        # 创建新人员记录
        new_person = {
            'name': name,
            'face_images': face_images or [],
            'created_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            'updated_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        self.data['persons'].append(new_person)
        if self.save():
            return True, f"已添加人员 '{name}'"
        return False, "保存数据库失败"
    
    def remove_person(self, name):
        """删除人员"""
        if not validate_name(name):
            return False, "无效的人名"
            
        # 查找并删除人员
        for i, person in enumerate(self.data['persons']):
            if person['name'] == name:
                # 删除关联的人脸图像
                for image_path in person['face_images']:
                    try:
                        if os.path.exists(image_path):
                            os.remove(image_path)
                    except Exception as e:
                        logging.error(f"删除人脸图像失败 {image_path}: {e}")
                
                # 从数据库中删除
                self.data['persons'].pop(i)
                if self.save():
                    return True, f"已删除人员 '{name}'"
                return False, "保存数据库失败"
        
        return False, f"未找到人员 '{name}'"
    
    def add_face_image(self, name, image_path):
        """为指定人员添加人脸图像"""
        if not validate_name(name):
            return False, "无效的人名"
            
        if not os.path.exists(image_path):
            return False, "图像文件不存在"
            
        # 查找人员
        for person in self.data['persons']:
            if person['name'] == name:
                person['face_images'].append(image_path)
                person['updated_at'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                if self.save():
                    return True, f"已为 '{name}' 添加人脸图像"
                return False, "保存数据库失败"
        
        return False, f"未找到人员 '{name}'"
    
    def get_all_persons(self):
        """获取所有人员信息"""
        return self.data['persons']
    
    def get_person(self, name):
        """获取指定人员信息"""
        if not validate_name(name):
            return None
            
        for person in self.data['persons']:
            if person['name'] == name:
                return person
        return None
    
    def clear(self):
        """清空数据库"""
        # 删除所有人脸图像
        for person in self.data['persons']:
            for image_path in person['face_images']:
                try:
                    if os.path.exists(image_path):
                        os.remove(image_path)
                except Exception as e:
                    logging.error(f"删除人脸图像失败 {image_path}: {e}")
        
        # 重置数据库
        self.data = {'persons': [], 'version': '1.0'}
        return self.save() 